var app = {
    LAYUI_WINDOW_OPEND:false,
    //BASE_API_URL:'https://192.168.50.101/crm/',
    BASE_API_URL:'https://192.168.199.199/crm/',
    DEFAULT_ALL_VALUE:"!@w3e4rt98520",
    DIV:1000000,
    DIV_LEN:6,
    orderTypes:{"a1":"采购订单","a3":"普通采购","a4":"采购退货","a20":"销售订单","a22":"普通销售","a23":"销售退货","a50":"其它入库","a51":"其他出库","a52":"库存盘点","a53":"库存调拨","a54":"库存拆装","a80":"收款单","a81":"付款单","a82":"其他收入","a83":"其他支出","a84":"核销","a85":"资金转账"},
    productArea:['920px', '600px'],
    relationArea:['820px', '600px'],
    getBaseUrl:function(){
        var a = location.href;
        return a.substring(0,a.indexOf(app.BASE_API_URL)+6);
    },
    getServerTime:function(){
        var clientCurrTime = new Date().getTime();
        return top.serverTime+(clientCurrTime-top.clientTime);
    },
    getServerDate:function(){
        return new Date(app.getServerTime());
    },
    transNumber:function(num){
        return (num+"").replace('.00','');
    },
    getDictValue:function(code){
        for( var i=0 ; i < top.dicts.length ; i++ ){
            if( top.dicts[i].code == code ){
                return top.dicts[i].value;
            }
        }
    },
    actionSuccess_index:function(resp,index){
        if( resp.result==0 ){
            app.message(layer,'操作成功');
            $("#table").datagrid("reload");
            layer.close(index);
        }else{
            app.message(layer,'操作失败【'+app.getErrorMsg(resp)+'】',2);
        }
        layer.close(index);
    },
    actionSuccess:function(resp){
        app.actionSuccess_common(resp,window);
    },
    actionSuccess_parent:function(resp){
        app.actionSuccess_common(resp,parent);
    },
    actionSuccess_common:function(resp,win){
        if( resp.result==0 ){
            app.closeLastWindow();
            app.message(win.layer,'操作成功');
            win.$("#table").datagrid("reload");
        }else{
            win.layer.close(win.layer.index);
            app.message(win.layer,'操作失败【'+app.getErrorMsg(resp)+'】',2);
        }
    },
    getErrorMsg:function(resp){
        var message = top.bussError['code'+resp.result];
        if(!message){
            message = top.bussError['code'+resp.data];
        }
        if(!message){
            message = resp.data;
        }
        return message;
    },
    getOperation:function(id,name,type,clickFnName){
        var operation = $('<span class="table-op-btn">&nbsp;</span>');
        if(id){
            operation.empty();
            var a = $('<a data-id="'+id+'" href="javascript:void(0);" onclick="'+clickFnName+'(this)" class="vui-opt vui-opt-'+type+'">'+name+'</a>');
            operation.append(a);operation.attr('title',name);
        }
        return operation;
    },
    message:function(layer,message){
        layer.msg('<span style="color:#FFFFFF;">'+message+'</span>');
    },
    getErrorMessage:function(resp){
        var message = top.bussError['code'+resp.result];
        if(!message){
            message = top.bussError['code'+resp.data];
        }
        if(!message){
            message = resp.data;
        }
        return message;
    },
    getOpt:function(id,name,type,title){
        if(title){
            return '<span class="table-op-btn" title="'+title+'"><a data-id="'+id+'" class="vui-opt vui-opt-'+type+'">'+name+'</a></span>';
        }else{
            return '<span class="table-op-btn"><a data-id="'+id+'" class="vui-opt vui-opt-'+type+'">'+name+'</a></span>';
        }
    },
    getHideOpt:function(count){
        var v = '';
        for( var i=0 ; i<count ; i++ ){
            v += '中';
        }
        return '<span class="table-op-btn" style="visibility: hidden;"><a class="vui-opt">'+v+'</a></span>';
    },
    resetForm:function(data){
        $('#formArea input').each(function(){
            var value = data[this.name];
            if(value){
                var n = $(this).attr('n');
                if(n=='money'){
                    $(this).val(app.div(value,app.DIV));
                }else if(n=='date'){
                    $(this).val(app.time2str(parseInt(value)));
                }else{
                    $(this).val(value);
                }
            }
        });

        $('#formArea textarea').each(function(){
            if(data[this.name]){
                $(this).val(data[this.name]);
            }
        });
    },
    getLogin:function(){
        return {customerId:top.customerId,loginCompanyId:top.loginCompanyId,loginCompanyLogicalCode:top.loginCompanyLogicalCode,loginUserId:top.loginUserId,loginCompanyName:top.loginCompanyName,loginName:top.loginName};
    },
    getCompanyId:function () {
        return app.getLogin().loginCompanyId;
    },
    getCompanyName:function () {
        return app.getLogin().companyName;
    },
    getElementPoint :function (ele) {
        var y = ele.offset().top;
        var x = ele.offset().left;
        return {x:x,y:y};
    },
    closeLastWindow:function(){
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
    },
    shows:function(eles){
        for( var i=0 ; i<eles.length ; i++ ){
            $(eles[i]).show();
        }
    },
    hides:function(eles){
        for( var i=0 ; i<eles.length ; i++ ){
            $(eles[i]).hide();
        }
    },
    window:function(layer,options){
        var setting = {
            type: 2,
            area: ['500px', '300px'],
            fixed: false, //不固定
            maxmin: true,
            btn:['确认','取消'],
            yes:function(){
                return false;
            }
        };

        $.extend(setting,options);

        return layer.open(setting);
    },
    getRequestParams:function () {
        var o = {};
        var href = location.href;
        if(href.indexOf('?')==-1){
            return o;
        }
        href = href.substr(href.indexOf('?')+1);
        href = href.split('&');
        $.each(href,function (i,row) {
            var arr = row.split('=');
            o[arr[0]] = decodeURIComponent(arr[1]);
        });
        return o;
    },
    setRequestParams:function(params){
        var url = '';
        for( var n in params ){
            url += "&"+n+"="+params[n];
        }
        return url;
    },
    getLable:function(name,type){
        return '<span class="label-status label-'+type+'">'+name+'</span>';
    },
    timeFormatter:function(row,value){
        return app.time2str(value);
    },
    time2str:function(inputTime) {

        if( inputTime == null || inputTime==-1 || $.trim(inputTime).length==0){
            return '';
        }

        var type = typeof(inputTime);
        var date = type == 'object'?inputTime:type == 'number'?new Date(inputTime):type == 'string'?new Date(parseInt(inputTime)):inputTime;
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        /*var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;*/
        return y + '-' + m + '-' + d;
    },
    request:function(options){
        var setting = {
            type:'POST',
            dataType:'json',
            error:function(){
                layer.closeAll('loading');
            }
        };
        $.extend(setting,options);
        setting.url = app.BASE_API_URL+setting.url;
        setting.data =$.extend(options.data,{loginUserId:top.loginUserId,customerId:top.customerId,loginCompanyId:top.loginCompanyId,loginCompanyLogicalCode:top.loginCompanyLogicalCode});
        setting.success = function(resp){
            if( resp.result == 2 ){
                top.layer.confirm('无权限或者登陆过期，即将跳转到登陆界面', {icon: 3, title:'提示'}, function(index){
                    app.toLogin();
                    layer.close(index);
                });
            }else{
                options.success(resp);    
            }
        }

        $.ajax(setting);
    },
    toLogin:function(){
        top.location.href = "/html/index/login.html";
    },
    menuClick:function(){

    },
    getOkBtn:function(){
        return $('.layui-layer-btn0',parent.document);
    },
    serializeForm:function(){
        var data = {};
        $('#formArea input,#formArea textarea').each(function(){
            var n = $(this).attr('n');
            var value = this.value;
            if( value == app.DEFAULT_ALL_VALUE ){
                value = "";
            }
            if( n=='money' ){
                if(value!=null && value!=undefined && value.length > 0 ){
                    data[this.name] = parseInt(app.mul(value+"",app.DIV));
                }
            }else if(n=='date'){
                if(value!=null && value!=undefined && value.length > 0 ){
                    if( this.name == 'dateEnd' ){
                        data[this.name] = new Date(value+' 23:59:59').getTime();
                    }else{
                        data[this.name] = new Date(value).getTime();
                    }

                }

            }else{
                data[this.name] = value;
            }

        });

        $('#formArea input[type="radio"]').each(function(){
            data[this.name] = $('input[name="'+this.name+'"]:checked').val();
        });

        return data;
    },
    msg:function(layer,msg){
        layer.msg('<span style="color:#FFFFFF;">'+msg+'</span>');
    },
    showExam:function (gridId) {
        var examDiv = $('.exam');
        if( examDiv.length > 0 ){
            examDiv.show();
        }else{
            $(document.body).append('<div class="exam">已审核</div>');
            $('.exam').css({"bottom":"20px","right":"20px"});
        }
    },
    hideExam:function () {
        $('.exam').hide();
    },
    checkForm:function(options){
        for( var i=0 ; i<options.length ; i++ ){
            var option = options[i];
            var value = null;

            var labelName = option.type;
            var elem = $(labelName+'[name="'+option.name+'"]');
            if(elem.length==0){
                alert('check form query string error');
            }
            value = elem.val();
            value = $.trim(value);

            for( var j=0 ; j<option.verify.length ; j++ ){
                var verify = option.verify[j];
                if( verify.type=='required' ){
                    if( !value ){
                        layer.tips('必填项', labelName+'[name="'+option.name+'"]', {
                            tips: [1, '#3595CC'],
                            time: 3000
                        });
                        $(labelName+'[name="'+option.name+'"]').focus();
                        return false;
                    }
                }else if( verify.type=='length' ){
                    if( value && value.length > verify.value ){
                        layer.tips('最多输入'+verify.value+'个字符', labelName+'[name="'+option.name+'"]', {
                            tips: [1, '#3595CC'],
                            time: 3000
                        });
                        $(labelName+'[name="'+option.name+'"]').focus();
                        return false;
                    }
                }else if( verify.type=='decimal' ){
                    var regu = /^[0-9]+\.?[0-9]{0,2}$/;
                    if( value && !regu.test(value) ){
                        layer.tips('只能输入数字，最大两位小数', labelName+'[name="'+option.name+'"]', {
                            tips: [1, '#3595CC'],
                            time: 3000
                        });
                        $(labelName+'[name="'+option.name+'"]').focus();
                        return false;
                    }
                }


            }

        }

        return true;
    },
    //加
    add:function (arg1,arg2,decimal){
        if(decimal==undefined){decimal = 2;}

        var r1,r2,m;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2));
        return ((arg1*m+arg2*m)/m).toFixed(decimal);
    },
    //减
    sub:function (arg1,arg2,decimal){
        if(decimal==undefined){decimal = 2;}
        var r1,r2,m;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2));
        return ((arg1*m-arg2*m)/m).toFixed(decimal);
    },
    //乘
    mul:function (arg1,arg2,decimal)   {
        if(decimal==undefined){decimal = 2;}
        var m=0,s1=arg1.toString(),s2=arg2.toString();
        try{m+=s1.split(".")[1].length}catch(e){}
        try{m+=s2.split(".")[1].length}catch(e){}
        return (Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)).toFixed(decimal);
    },
    //除
    div:function (arg1,arg2,decimal){
        if(decimal==undefined){decimal = 2;}
        var t1=0,t2=0,r1,r2;
        try{t1=arg1.toString().split(".")[1].length}catch(e){}
        try{t2=arg2.toString().split(".")[1].length}catch(e){}

        r1=Number(arg1.toString().replace(".",""));

        r2=Number(arg2.toString().replace(".",""));
        return ((r1/r2)*Math.pow(10,t2-t1)).toFixed(decimal);
    }
};

function deletePrefix(value){
    if( value == null || value == undefined || $.trim(value).length==0 ){
        return "";
    }
    var result='',p1 = /[0-9]/;
    for( var i = 0 ; i<value.length ; i++ ){
        if( p1.test(value[i]) ){
            result += value[i];
        }
    }
    return result;
}

Array.prototype.merge = function(arr){
    for( var i=0 ; i<arr.length ; i++ ){
        this.push(arr[i]);
    }
};

$(function(){

    $('input[n="money"]').focus(function () {
        if($(this).attr('readonly')){
            return;
        }
        try {
            $(this).select();
            this.selectionStart = 0;
            this.selectionEnd = this.val().length;
        } catch (e) {
        }
    });

    $('input[n="money"][readonly="readonly"]').css({"background-color":"#dcdcdc"});

    $('input[n="money"]').blur(function () {
        var value = $(this).val();
        if( value!=null && $.trim(value).length>0 ){
            value = parseFloat(value);
            if(isNaN(value)){
                $(this).val('0.00');
            }else{
                $(this).val(parseFloat(value).toFixed(2));
            }
        }else{
            $(this).val('0.00');
        }
    });

    $(document.body).click(function (e) {
        $('.fly[tg]').hide();
        editAfterEvent(e);
    });

    setTimeout("$(window).scrollTop(0)",200);
});



function editAfterEvent(e) {
    comboAfterEvent();
    editDateAfterEvent(e);
    editComboAfterEvent();
    editSearchAfterEvent(e);
}

function editSearchAfterEvent(e) {
    if(top.app.LAYUI_WINDOW_OPEND)return;
    var cellSearch = $('div[role="search"]');
    cellSearch.parent().html(cellSearch.find('input[type="text"]').val());
    cellSearch.remove();
}

function editComboAfterEvent() {
    var combobox = $('div[role="combobox"]');
    if( combobox.length == 0 )return;
    var value = combobox.find('input[type="hidden"]').val();
    var text = combobox.find('input[type="text"]').val();
    var cell = combobox.parent();
    cell.data({value:value,text:text});
    cell.empty().html(text);
}

function editDateAfterEvent(e) {
    var className = e.target.className;
    if( className == 'input-date' || className == 'vui-table-cell' ){
        return;
    }
    var input = $('.input-date');
    if( input.length > 0 ){
        var value = input.val();
        input.parent().html(value);
    }
}

function comboAfterEvent() {
    var comboBody =  $(document.body).find('.combobox-body');
    if(comboBody.length==0)return;
    $('input[name="'+comboBody.data().name+'"]').parent().find('i').removeClass("fa-angle-up").addClass("fa-angle-down");
    comboBody.remove();
}